package com.example.demo.service;

import com.example.demo.mapper.ActiveMapper;
import com.example.demo.mapper.EmployeeCommentMapper;
import com.example.demo.mapper.EmployeeMapper;
import com.example.demo.mapper.OlderMapper;
import com.example.demo.model.*;
import com.example.demo.tools.Constant;
import com.example.demo.tools.EncryptionTool;
import com.example.demo.tools.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: WJ
 * Date: 2023-02-17
 * Time: 21:37
 */
@Service
public class EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private ActiveMapper activeMapper;

    @Autowired
    private OlderMapper olderMapper;

    @Autowired
    private EmployeeCommentMapper employeeCommentMapper;

    @Autowired
    private EncryptionTool encryptionTool;     // 加密工具

    @Autowired
    private RedisUtil redisUtil;


//    员工权限时，首页的table数据
    public Object getPersonTable(LoginUser user) {
        List<LoginUser> employeeList = employeeMapper.getAllPersonInfoExceptAdmin();
        if(employeeList != null){
            return employeeList;
        }
        return "查询除管理员之外的所有人员信息失败!";
    }

//    通过员工id获取手下的老人列表信息
    public Object getOlderListByEmployeeId(Integer id) {
        List<Older> olderList = olderMapper.getOlderListByEmployeeId(id);
        if(olderList != null){
            return olderList;
        }

        return "查询老人信息失败!";
    }

//   在员工管理中的老人管理对话框中删除老人信息
    public Object deleteOlderInfoByOlderId(Integer olderId) {
        // 1. 删除person中的老人信息
        Integer n1 = olderMapper.deleteOlderInPerson(olderId);
        // 2. 删除older_detail中的老人详细信
        Integer n2 = olderMapper.deleteOlderInOlderDetail(olderId);
        // 3. 删除employee_older表中的详情
        Integer n = employeeCommentMapper.deleteEmployeeOlderByOlderId(olderId);
        if(n1 == 1 && n2 == 1 && n == 1){
            return true;
        }
        return "删除老人失败";
    }

//    获取所有的员工信息
    public Object getAllEmployeeList() {
        List<LoginUser> list = employeeMapper.getEmployeeList(null);
        if(list != null){
            return list;
        }
        return "员工信息获取失败!";
    }

//    变更老人的上属员工
    public Object changeOlderTheEmployee(Integer employeeId, Integer olderId) {
        Integer n = olderMapper.updateOlderTheEmployee(employeeId, olderId);
        // 更新该老人对新员工的评价状态
        Integer n2 = employeeCommentMapper.updateEmployeeIdByOlderId(employeeId, olderId);
        if(n == 1 && n2 == 1){
            return true;
        }
        return "变更失败!";
    }

//    添加员工
    public Object addEmployee(String username, String sex, Integer age, String address, String phone, String area, String id_card, Integer admin_id, String photo_url) {
        String encrypt = encryptionTool.encrypt("111111");

        Employee employee = new Employee();
        employee.setUsername(username);
        employee.setSex(sex);
        employee.setAge(age);
        employee.setPhone(phone);
        employee.setPassword(encrypt);         // 加密后的密码

        if(photo_url == null || "".equals(photo_url)){
            // 添加默认头像
            employee.setPhoto_url("https://pension-system-wj.oss-cn-beijing.aliyuncs.com/images/employee.png");
        }else{
            // 添加自己上传的头像
            employee.setPhoto_url(photo_url);
        }
        Integer result = employeeMapper.addEmployeeOnPerson(employee);
        if(result == 1){
            Integer n = employeeMapper.addEmployeeOnEmployeeDetail(employee.getId(), admin_id, id_card, address, area);
            if(n == 1){
                return true;
            }
        }
        return "添加员工失败!";
    }

//    根据条件查询（员工模块的查询）
    public Object getAllEmployeeInfoByUsernameOrAgeD(Integer id, String username, String phone, String sex, Integer age) {
        List<Employee> employeeList = employeeMapper.getAllEmployeeByAdminIdLike(id, username, phone, sex, age);
        if(employeeList != null){
            return employeeList;
        }
        return "查询员工信息失败!";
    }

//    活动管理下的活动审批模块里的查询:查询当前管理员下的所有活动信息
    public Object getAllActiveInfoByItems(Integer id,String start_time, String end_time, String active_name, Integer applicant) {

        try {
            Calendar calendar = new GregorianCalendar();
            SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
            SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            if(!"".equals(start_time)){
                // 给start_time加一天
                Date dateStart = inputFormat.parse(start_time);
                calendar.setTime(dateStart);
                calendar.add(Calendar.DATE, 1);
                dateStart = calendar.getTime();
                start_time = outputFormat.format(dateStart);
            }
            if(!"".equals(end_time)){
                // 给end_time加一天
                Date dateEnd = inputFormat.parse(end_time);
                calendar.setTime(dateEnd);
                calendar.add(Calendar.DATE, 1);
                dateEnd = calendar.getTime();
                end_time = outputFormat.format(dateEnd);
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }

        List<Active> actives = activeMapper.getAllActiveInfoByItems(id, start_time, end_time, active_name, applicant);
        if(actives != null){
//            查找员工名
            for (Active active:actives) {
                List<LoginUser> employeeList = employeeMapper.getEmployeeList(active.getActive_employee());
                active.setActive_employee_name(employeeList.get(0).getUsername());
            }
            return actives;
        }
        return "查询活动信息失败了!";
    }

//    查询所有活动详情(可以通过 开始时间 结束时间 的范围查找,也可以根据 active_name 来模糊查询)
    public Object getAllActiveInfoInActiveDetail(String begin_start_time, String begin_end_time, String finish_start_time, String finish_end_time, String active_name) {

        try {
            Calendar calendar = new GregorianCalendar();
            SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
            SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            if(!"".equals(begin_start_time)){
                // begin_start_time 加一天
                Date beginDateStart = inputFormat.parse(begin_start_time);
                calendar.setTime(beginDateStart);
                calendar.add(Calendar.DATE, 1);
                beginDateStart = calendar.getTime();
                begin_start_time = outputFormat.format(beginDateStart);
            }
            if(!"".equals(begin_end_time)){
                // begin_end_time 加一天
                Date beginDateEnd = inputFormat.parse(begin_end_time);
                calendar.setTime(beginDateEnd);
                calendar.add(Calendar.DATE, 1);
                beginDateEnd = calendar.getTime();
                begin_end_time = outputFormat.format(beginDateEnd);
            }
            if(!"".equals(finish_start_time)){
                // finish_start_time 加一天
                Date finishDateStart = inputFormat.parse(finish_start_time);
                calendar.setTime(finishDateStart);
                calendar.add(Calendar.DATE, 1);
                finishDateStart = calendar.getTime();
                finish_start_time = outputFormat.format(finishDateStart);
            }
            if(!"".equals(finish_end_time)){
                // finish_end_time 加一天
                Date finishDateEnd = inputFormat.parse(finish_end_time);
                calendar.setTime(finishDateEnd);
                calendar.add(Calendar.DATE, 1);
                finishDateEnd = calendar.getTime();
                finish_end_time = outputFormat.format(finishDateEnd);
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }

        List<Active> activeList = activeMapper.getAllActiveInfoForActiveDetail(begin_start_time, begin_end_time, finish_start_time, finish_end_time, active_name);
        if(activeList != null){
//            查找员工名
            for (Active active:activeList) {
                List<LoginUser> employeeList = employeeMapper.getEmployeeList(active.getActive_employee());
                active.setActive_employee_name(employeeList.get(0).getUsername());
            }
            return activeList;
        }
        return "查询活动信息失败了!";
    }

//    查询所有员工信息(person 和 employee_detail两表联查)
    public Object getAllEmployeeInfo() {
        List<Employee> employeeList = employeeMapper.getAllEmployeeInfo();
        if(employeeList != null){
            return employeeList;
        }
        return "查询所有员工信息失败!";
    }

    //    修改员工信息
    public Object updateAdminInfo(Integer id, String username, String password, String sex, Integer age, String phone, String url,String address) {
        Integer result = -1;
        if(password == null || "".equals(password)){
            // 不修改密码
            result = employeeMapper.updateEmployeeInfoInPerson(id, username, null, sex, age, phone, url);
        }else{
            // 给密码加密
            String encrypt = encryptionTool.encrypt(password);
            result = employeeMapper.updateEmployeeInfoInPerson(id, username, encrypt, sex, age, phone, url);
        }
        if(result == 1){
            // 更新 employee_detail 中的信息
            Integer n = employeeMapper.updateEmployeeInfoInDetail(id, address);
            if(n == 1){
                // 1.移除session中的信息
                redisUtil.deleteObject(Constant.USER_LOGIN+id);
                return true;
            }
        }
        return "修改员工信息失败!";
    }

//    申请活动
    public Object addActiveOnEmployee(String active_name, String active_address, String start_time, String end_time, String context, String summary, Integer employee_id, Integer admin_id, String p1, String p2) {

        // 处理时间
        try {
            Calendar calendar = new GregorianCalendar();
            SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
            SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            // start_time 加一天
            Date startDate = inputFormat.parse(start_time);
            calendar.setTime(startDate);
            calendar.add(Calendar.DATE, 1);
            startDate = calendar.getTime();
            start_time = outputFormat.format(startDate);

            // end_time 加一天
            Date endDate = inputFormat.parse(end_time);
            calendar.setTime(endDate);
            calendar.add(Calendar.DATE, 1);
            endDate = calendar.getTime();
            end_time = outputFormat.format(endDate);

        } catch (ParseException e) {
            e.printStackTrace();
        }

        Integer n = activeMapper.addActiveOnEmployee(active_name, active_address, start_time, end_time, context, summary, employee_id, admin_id, p1, p2);
        if(n == 1){
            return true;
        }
        return "申请活动失败!";
    }

//    获取当前登录员工的所有申请活动列表
    public Object getActiveOnCurrentEmployeeId(Integer id) {
        List<Active> activeList = activeMapper.getAllActiveInfoByEmployeeId(id);
        if(activeList != null){
            return activeList;
        }
        return "获取员工申请的活动列表失败!";
    }

//    对报名参加活动的老人进行审批（通过）
    public Object olderJoinActiveProveOnAllow(Integer id) {
        // 1. 修改 older_join_active 的审批状态
        Integer result = activeMapper.updateOlderJoinActiveInfo(id, "已通过");
        if(result != 1){
            return "报名信息审批失败!";
        }
        // 2. 查询 older_id 和 active_id 在 older_join_active 表中
        ActiveOlder obj = activeMapper.getOlderIdAndActiveId(id);
        if(obj == null){
            return "报名信息审批失败!";
        }
        // 3. 在 active_older 表中插入通过的数据
        Integer n = activeMapper.addInfoOnActiveOlder(obj.getOlder_id(), obj.getActive_id(), "报名成功");
        if(n != 1){
            return "报名信息审批失败!";
        }
        return true;
    }

//    对报名参加活动的老人进行审批（拒绝）
    public Object olderJoinActiveProveOnrefuse(Integer id) {
        // 1. 修改 older_join_active 的审批状态
        Integer result = activeMapper.updateOlderJoinActiveInfo(id, "已拒绝");
        if(result != 1){
            return "报名信息审批失败!";
        }
        // 2. 查询 older_id 和 active_id 在 older_join_active 表中
        ActiveOlder obj = activeMapper.getOlderIdAndActiveId(id);
        if(obj == null){
            return "报名信息审批失败!";
        }
        // 3. 在 active_older 表中插入拒绝的数据
        Integer n = activeMapper.addInfoOnActiveOlder(obj.getOlder_id(), obj.getActive_id(), "报名失败");
        if(n != 1){
            return "报名信息审批失败!";
        }
        return true;
    }
}
